<template>
  <div class="container">
    <ButtonGroup :options="buttons" @click="handleButtonClick" />
    <p-table
      class="table-list-container"
      row-key="id"
      :custom-header-row="customHeaderRowMinxin"
      :columns="columns"
      bordered
      :scroll="{ x: '100%', y: 300 }"
      :pagination="false"
      :data-source="totalData"
      :row-selection="rowSelectionMixin"
      @change="handleTableChange"
    >
      <!-- <template slot="customerCode" slot-scope="text, record, index">
        <DialogUserList
          :value="text"
          :visible.sync="visibleCustomer"
          @change="
            handleInputChange($event, text, record, index, 'customerCode')
          "
        />
        <InputSearch :value="text" @search="visibleCustomer = true" />
      </template> -->
      <!-- <template slot="salesGroupName" slot-scope="text, record, index">
        <SelectDefault
          :value="text"
          :options="saleGroupOptions"
          :has-all="false"
          @input="
            handleInputChange($event, text, record, index, 'salesGroupName')
          "
        />
      </template> -->
      <!-- <template slot="item" slot-scope="text, record, index">
        <InputDefault
          :value="text"
          @change="handleInputChange($event, text, record, index, 'item')"
        />
      </template>
      <template slot="innerItem" slot-scope="text, record, index">
        <InputDefault
          :value="text"
          @change="handleInputChange($event, text, record, index, 'innerItem')"
        />
      </template> -->
      <!-- <template slot="modelNumber" slot-scope="text, record, index">
        <DialogChooseModelType
          :value="text"
          :visible.sync="visibleModelNumber"
          @change="
            handleInputChange($event, text, record, index, 'modelNumber')
          "
        />
        <InputSearch
          :value="text"
          width="100px"
          @search="visibleModelNumber = true"
        />
      </template> -->
      <!-- <template slot="modelName" slot-scope="text, record, index">
        <DialogChooseModelType
          :value="text"
          :visible.sync="visibleModelName"
          @change="handleInputChange($event, text, record, index, 'modelName')"
        />
        <InputSearch
          :is-input="true"
          :value="text"
          @search="visibleModelName = true"
        />
      </template> -->
      <!-- <template slot="application" slot-scope="text, record, index">
        <SelectDefault
          :value="text"
          code="application"
          :has-all="false"
          @input="handleInputChange($event, text, record, index, 'application')"
        />
      </template> -->
      <!-- <template slot="appearance" slot-scope="text, record, index">
        <SelectDefault
          :value="text"
          code="shape"
          :has-all="false"
          @input="handleInputChange($event, text, record, index, 'appearance')"
        />
      </template> -->
      <!-- <template slot="manufactureArea" slot-scope="text, record, index">
        <SelectDefault
          :value="text"
          code="production_place"
          :has-all="false"
          @input="
            handleInputChange($event, text, record, index, 'manufactureArea')
          "
        />
      </template> -->
      <!-- <template slot="modelCutRate" slot-scope="text, record, index">
        <InputNumber
          :value="text"
          @change="
            handleInputChange($event, text, record, index, 'modelCutRate')
          "
        />
      </template>
      <template slot="remark" slot-scope="text, record, index">
        <InputDefault
          :value="text"
          @change="handleInputChange($event, text, record, index, 'remark')"
        />
      </template> -->
    </p-table>
    <DialogFiledFilter
      :visible.sync="visibleFiled"
      :fileds="fileds"
      @confirm="handleSelectFileds"
    />
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import { createMonthArray } from '@/utils/time';
import DialogUserList from '@/components/dialog/DialogUserList.vue';
import DialogChooseModelType from '@/components/dialog/DialogChooseModelType.vue';
import DialogModelNameList from '@/components/dialog/DialogModelNameList.vue';
import DialogFiledFilter from '@/components/dialog/DialogFiledFilter.vue';
import Decimal from 'decimal.js';

let index = 0;

export default {
  components: {
    DialogFiledFilter,
  },
  mixins: [mixinTable],
  props: {
    parentId: {
      type: [String, Number],
      default: undefined,
    },
    timeRange: {
      type: Array,
      default: () => ['2021-01', '2021-05'],
    },
    hideKeys: {
      type: Array,
      default: () => ['salesGroupName'],
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    planSales: {
      type: Array,
      default: () => [],
    },
    buttons: {
      type: Array,
      default: () => [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
          icon: 'plus',
        },
        {
          key: 'copy',
          label: '复用',
        },
        {
          key: 'delete',
          label: '删除',
        },
        {
          key: 'insert',
          label: '导入',
        },
        {
          key: 'download',
          label: '下载模板',
        },
        // {
        //   key: 'show',
        //   label: '显示字段',
        // },
      ],
    },
  },
  data() {
    return {
      visibleFiled: false,
      visibleCustomer: false,
      visibleModelNumber: false,
      visibleModelName: false,
      filedsKeys: [],
      currentRowInfo: {},
    };
  },
  computed: {
    totalData() {
      if (!this.dataSource.length) return [];
      const totalKeys = Object.keys(this.dataSource[0]).filter((item) =>
        item.includes('month_')
      );

      const obj = this.dataSource.reduce(
        (pre, cur) => {
          totalKeys.forEach((key) => {
            if (!pre[key]) {
              pre[key] = 0;
            }
            pre[key] = new Decimal(pre[key])
              .plus(new Decimal(cur[key] || 0))
              .toFixed();
          });
          return pre;
        },
        { id: 'totalKey' }
      );

      return [...this.dataSource, { ...this.dataSource[0], ...obj }];
    },
    saleGroupOptions() {
      return this.planSales.map((item) => {
        return {
          value: item.salesGroupName,
          label: item.salesGroupName,
        };
      });
    },
    ranges() {
      return createMonthArray(this.timeRange);
    },
    colIndex() {
      return this.columns.findIndex((item) => item.dataIndex === 'quantity');
    },
    defaultCoulumns() {
      return [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 60,
          customRender: (t, r, index) => {
            if (index < this.totalData.length - 1) {
              return parseInt(index) + 1;
            }
            return {
              children: (
                <div style="display: flex;justify-content: flex-start;">
                  总计
                </div>
              ),
              attrs: {
                colSpan: this.colIndex,
              },
            };
          },
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupName',
          required: true,
          width: 120,
          isHide: this.hideKeys.includes('salesGroupName'),
          customRender: (value, row, index) => {
            const children = (
              <SelectDefault
                value={value}
                options={this.saleGroupOptions}
                has-all={false}
                vOn:input={(e) =>
                  this.handleInputChange(e, value, row, index, 'application')
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerCode',
          required: true,
          width: 120,
          scopedSlots: { customRender: 'customerCode' },
          customRender: (value, row, index) => {
            const children = (
              <div>
                <DialogUserList
                  value={value}
                  visible={this.visibleCustomer}
                  vOn:cancel={(val) => (this.visibleCustomer = val)}
                  vOn:change={(e) => this.confirmDialog(e)}
                />
                <InputSearch
                  value={value}
                  vOn:search={() =>
                    this.openDialog('visibleCustomer', {
                      value,
                      row,
                      index,
                      dataIndex: 'customerCode',
                    })
                  }
                />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <InputDefault
                value={value}
                vOn:change={(e) =>
                  this.handleInputChange(e, value, row, index, 'item')
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <InputDefault
                value={value}
                vOn:change={(e) =>
                  this.handleInputChange(e, value, row, index, 'innerItem')
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelNumber',
          required: true,
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <DialogChooseModelType
                  value={value}
                  visible={this.visibleModelNumber}
                  vOn:cancel={(val) => (this.visibleModelNumber = val)}
                  vOn:change={(e) => this.confirmDialog(e)}
                />
                <InputSearch
                  value={value}
                  width={'120px'}
                  vOn:search={() =>
                    this.openDialog('visibleModelNumber', {
                      value,
                      row,
                      index,
                      dataIndex: 'modelNumber',
                    })
                  }
                  vOn:change={(e) =>
                    this.handleInputChange(e, value, row, index, 'modelNumber')
                  }
                />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          required: true,
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <DialogModelNameList
                  value={value}
                  visible={this.visibleModelName}
                  info={this.currentRowInfo}
                  vOn:cancel={(val) => (this.visibleModelName = val)}
                  vOn:change={(e) => this.confirmDialog(e)}
                />
                <InputSearch
                  value={value}
                  isInput={true}
                  vOn:search={() =>
                    this.openDialog('visibleModelName', {
                      value,
                      row,
                      index,
                      dataIndex: 'modelName',
                    })
                  }
                  vOn:change={(e) =>
                    this.handleInputChange(e, value, row, index, 'modelName')
                  }
                />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          required: true,
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <SelectDefault
                value={value}
                code="application"
                has-all={false}
                vOn:input={(e) =>
                  this.handleInputChange(e, value, row, index, 'application')
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          required: true,
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <SelectDefault
                value={value}
                code="shape"
                has-all={false}
                vOn:input={(e) =>
                  this.handleInputChange(e, value, row, index, 'appearance')
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          dataIndex: 'manufactureArea',
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <SelectDefault
                value={value}
                code="production_place"
                has-all={false}
                vOn:input={(e) =>
                  this.handleInputChange(
                    e,
                    value,
                    row,
                    index,
                    'manufactureArea'
                  )
                }
              />
            );

            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          required: true,
          dataIndex: 'modelCutRate',
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <InputNumber
                value={value}
                vOn:change={(e) =>
                  this.handleInputChange(e, value, row, index, 'modelCutRate')
                }
              />
            );

            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          dataIndex: 'remark',
          width: 160,
          customRender: (value, row, index) => {
            const children = (
              <InputDefault
                value={value}
                vOn:change={(e) =>
                  this.handleInputChange(e, value, row, index, 'remark')
                }
              />
            );

            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'FCST',
          dataIndex: 'quantity',
          required: true,
          children: this.monthColumns('quantity'),
        },
        {
          align: 'center',
          title: '单价（人民币：元）',
          dataIndex: 'price',
          required: true,
          children: this.monthColumns('price'),
        },
      ];
    },
    fileds() {
      return this.defaultCoulumns;
    },
    columns() {
      let columns = this.defaultCoulumns.filter((item) => !item.isHide);
      if (this.filedsKeys.length) {
        columns = columns.filter((item) => {
          return item.required || this.filedsKeys.includes(item.dataIndex);
        });
      }
      return columns;
    },
  },
  created() {
    this.createDefaultItem();
    this.rowSelectionMixin.getCheckboxProps = (record) => {
      return {
        props: {
          disabled: record.id === 'totalKey',
        },
      };
    };
  },
  methods: {
    openDialog(dialog, rowInfo) {
      this[dialog] = true;
      this.currentRowInfo = rowInfo;
    },
    confirmDialog(e) {
      this.handleInputChange(
        e,
        this.currentRowInfo.value,
        this.currentRowInfo.row,
        this.currentRowInfo.index,
        this.currentRowInfo.dataIndex
      );
    },
    customRender(children, index, key) {
      const attrs = {};
      if (index === this.totalData.length - 1) {
        attrs.colSpan = 0;
      }
      return {
        children,
        attrs,
      };
    },
    handleSelectFileds(filedsKeys) {
      this.filedsKeys = filedsKeys;
    },
    createMonthObj() {
      return [...this.ranges, 'total'].reduce((pre, cur) => {
        pre[`pricemonth_${cur}`] = '';
        pre[`quantitymonth_${cur}`] = '';
        pre[`selfpricemonth_${cur}`] = '';
        pre[`selfnumbermonth_${cur}`] = '';
        return pre;
      }, {});
    },
    createDefaultItem() {
      return {
        id: `${index++}_customer`,
        item: '',
        innerItem: '',
        customerCode: { key: '', value: '' },
        modelNumber: { key: '', value: '' },
        modelName: { key: '', value: '' },
        application: '',
        appearance: '',
        manufactureArea: '',
        modelCutRate: '',
        remark: '',
        price: '',
        quantity: '',
        ...this.createMonthObj(),
        salesGroupName: '',
      };
    },
    totalAccount(type, record, index) {
      const result = Object.keys(record).reduce((pre, cur) => {
        if (cur.startsWith(type)) {
          const n = Number(record[cur]) || 0;
          pre = pre.plus(new Decimal(n));
        }
        return pre;
      }, new Decimal(0));
      return new Decimal(result).toFixed();
    },

    accountSelfPrice(row, dataIndex) {
      const date = dataIndex.split('_')[1];
      const price = Number(row[`pricemonth_${date}`]) || 0;
      const quantity = Number(row[`quantitymonth_${date}`]) || 0;
      const result = new Decimal(price)
        .mul(new Decimal(quantity))
        .div(100000000)
        .toFixed();
      row[dataIndex] = result;
      return result;
    },

    selfnumber(row, dataIndex) {
      const date = dataIndex.split('_')[1];
      const modelCutRate = Number(row.modelCutRate) || 0;
      const quantity = Number(row[`quantitymonth_${date}`]) || 0;
      let result = Math.ceil(quantity / modelCutRate) || 0;
      if (!Number.isFinite(result)) {
        result = 0;
      }
      row[dataIndex] = result;
      return result;
    },

    onInputChange(e, row, dataIndex) {
      row[dataIndex] = e;
    },

    monthColumns(key) {
      const price = (text, row, index, dataIndex) => {
        return (
          <InputNumber
            value={text}
            vOn:change={(e) =>
              this.handleInputChange(e, text, row, index, dataIndex)
            }
          />
        );
      };

      const selfprice = (text, row, index, dataIndex) => {
        if (index === this.totalData.length - 1)
          return <TableSpan value={text} />;
        return <TableSpan value={this.accountSelfPrice(row, dataIndex)} />;
      };

      const selfnumber = (text, row, index, dataIndex) => {
        if (index === this.totalData.length - 1)
          return <TableSpan value={text} />;
        return <TableSpan value={this.selfnumber(row, dataIndex)} />;
      };

      const renderMap = { price, quantity: price, selfprice, selfnumber };

      const list = this.ranges.map((item) => {
        const dataIndex = `${key}month_${item}`;
        return {
          align: 'center',
          title: item,
          width: 120,
          dataIndex,
          customRender: (text, row, index) =>
            renderMap[key](text, row, index, dataIndex),
        };
      });

      const totalKey = `${key}month_total`;
      const type = `${key}month`;
      list.push({
        align: 'center',
        title: '汇总',
        width: 120,
        dataIndex: totalKey,
        customRender: (text, row, index) => {
          return <TableSpan value={this.totalAccount(type, row)} />;
        },
      });
      list.unshift({
        align: 'center',
        title: '在途',
        width: 120,
        dataIndex: totalKey,
        customRender: (text, row, index) => {
          return <TableSpan value={this.totalAccount(type, row)} />;
        },
      });
      return list;
    },
    handleInputChange(e, text, record, index, key) {
      console.log('text, record, index: ', e, text, record, index);
      this.dataSource[index][key] = e;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(() => {
          ids.forEach((id) => {
            const index = this.dataSource.findIndex((item) => item.id === id);
            this.dataSource.splice(index, 1);
          });
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },
    addCallback() {
      console.log('this.dataSource: ', this.dataSource);
      this.dataSource.push({ ...this.createDefaultItem() });
    },
    copyCallback() {
      this.$message.error('复用功能暂未实现！');
    },
    insertCallback() {
      this.$message.error('导入功能暂未实现！');
    },
    downloadCallback() {
      this.$message.error('下载模板功能暂未实现！');
    },
    showCallback() {
      this.visibleFiled = true;
    },
    getstartCallback() {
      this.$emit('getstart');
    },
    saveTemplateCallback() {
      console.log('saveTemplateCallback: ', this.saveTemplateCallback);
      this.$message.success('cheng');
    },
  },
};
</script>

<style lang="less" scoped>
.poros-table td {
  white-space: nowrap;
}
.container {
  margin-bottom: 20px;
}
.table-list-container {
  margin-top: 10px;
}
</style>